<template>
  <div class="root">

    <!-- 头部 -->
    <div class="top">
      <div class="kaoshi">
        <h2>考试管理</h2>
      </div>
      <div @click="CaJN">
        <el-button type="primary">创建考试</el-button>
      </div>
    </div>

    <div>

      <!-- 表单 -->
      <div class="form">
        <el-space wrap>

          <span class="span">关键字</span>
          <div style="width: 140px;">
            <el-input v-model="data2.key" placeholder="请输入关键字" clearable />
          </div>

          <span>创建人</span>
          <div>
            <div style="width: 140px; ">
              <el-input v-model="data2.admin" placeholder="请输入创建人" clearable />
            </div>
          </div>

          <!-- 我创建的 -->
          <div>
            <el-checkbox label="我创建的" size="large" />
          </div>

          <span class="span2">开放时间</span>
          <div>
            <el-radio-group class="ml-4" v-model="timeRadio" @change="Radio">
              <el-radio label="1" size="large">永久开放</el-radio>
              <el-radio label="0" size="large">部分时段</el-radio>
            </el-radio-group>
          </div>

          <!-- 时间 -->
          <div style="width: 300px">
            <el-date-picker style="width: 280px" v-model="times"  type="daterange" unlink-panels range-separator="至"
              start-placeholder="开始时间" end-placeholder="结束时间" size="default" :shortcuts="shortcuts" :disabled="disabled"
              @change="time" />
          </div>

          <span>状态</span>
          <div>
            <el-select v-model="stateValue" clearable placeholder="选择状态" style="width: 100px" @change="sele">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>

          <div>
            <el-button type="primary" @click="search">查询</el-button>
          </div>

        </el-space>

      </div>

      <!-- 点击复选框让按钮显示 -->
      <div class="button">
        <div class="but_item" v-show="block !== 0">

          <el-popconfirm title="确认批量删除数据吗？" @confirm="getdell">
            <template #reference>
              <el-button type="danger">批量删除</el-button>
            </template>
          </el-popconfirm>

          <el-button type="primary" @click="Publish">发布考试</el-button>
          <el-button type="success" @click="cancel">取消发布</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <el-table class="custom-loading-svg" ref="multipleTableRef" :data="testArr" style="width: 100%"
        @selection-change="handleSelectionChange" empty-text="暂无数据" size="small">

        <el-table-column type="selection" width="55" />

        <el-table-column label="考试名称" show-overflow-tooltip>
          <template #default="scope">
            <el-link type="primary" @click="listdetails(scope.row.id, scope.row.title)">{{ scope.row.title }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column label="状态">
          <template #default="scope">
            <span :class="
              scope.row.state == 0 || scope.row.state == 1 ? 'blues' : 'reds'" @click="updstate(scope.row.state, scope.row.id)">
              {{scope.row.state === 0? '所有': scope.row.state === 1? '已发布': '未发布'}}
            </span>
          </template>
        </el-table-column>

        <el-table-column property="scores" label="总分" />
        <el-table-column property="pastscores" label="通过分数" />
        <el-table-column property="studentcounts" label="考试人数" />
        <el-table-column property="passCounts" label="通过人数" />

        <el-table-column property="begintime" label="开放时间" width="160px">
          <template #default="scope">
            <span style="font-size: 13px" v-if="scope.row.begintime == null">不限</span> <!--没有数据的时候显示不限-->
            <span style="font-size: 13px" v-else>
              {{ moment(scope.row.begintime).format('YYYY-MM-DD hh:mm') }}至
              {{ moment(scope.row.endtime).format('YYYY-MM-DD hh:mm') }}
            </span>
          </template>
        </el-table-column>

        <el-table-column property="admin" label="创建人" />
        <el-table-column property="addtime" label="更新时间" />

        <el-table-column label="操作" width="200px">
          <template #default="scope">
            <span style="font-size: 13px; cursor:pointer; color: #409eff" @click="studentUpd(scope.row.id)">学生</span>
            <el-divider direction="vertical" />
            <span style="font-size: 13px; cursor:pointer; color: #409eff" @click="SeeTeacherss(scope.row.id)">可见</span>
            <el-divider direction="vertical" border-style="dashed" />
            <span style="font-size: 13px; cursor:pointer; color: #409eff" @click="yueteacher(scope.row.id)">阅卷老师</span>
            <br />
            <span style="font-size: 13px; cursor:pointer; color: #409eff" @click="analysisTest(scope.row)">分析</span>
            <el-divider direction="vertical" border-style="dashed" />
            <span style="font-size: 13px; cursor:pointer; color: #409eff" @click="updTest(scope.row.id, scope.row)">编辑</span>
            <el-divider direction="vertical" border-style="dashed" />
            <!-- <span style="font-size: 13px; cursor:pointer; color: #f54848" @click="getdel(scope.row.id)">删除</span> -->

            <el-popconfirm title="确认删除该数据吗？" @confirm="getdel(scope.row.id)">
              <template #reference>
                <span style="font-size: 13px; cursor:pointer; color: #f54848">删除</span>
              </template>
            </el-popconfirm>

          </template>
        </el-table-column>
        
      </el-table>

      <!-- 分页 -->
      <div class="fenye">
        <FenYe :total="totals" @getChildData='getChildData'></FenYe>
      </div>


      <!-- 考试名称 详情 -->
      <Listdetails :detailsList="detailsList" v-if="detailsList == true" @closedetailsList="closedetailsList" :getid="getid" :title="title"></Listdetails>

      <!-- 学生 -->
      <Examinee :showStudent="showStudent" v-if="showStudent == true" @StudenthandleClose="StudenthandleClose"
      @StudentCancels="StudentCancels" @StudentConfirms="StudentConfirms" :testId="testId"></Examinee>

      <!-- 可见老师 -->
      <seeteacherLook :isshow="isshow" v-if="isshow == true" :seeid="seeid" @handleClose="handleClose"
      @cancel="Cancel2" @Confirm="Confirm"></seeteacherLook>

      <!-- 阅卷老师 -->
      <yueTeacherUpd :isshow2="isshow2" v-if="isshow2 == true" :seeid2="seeid2" @handleClosec="handleClosec"
      @cancel="Cancel3" @Confirm="Confirm3"></yueTeacherUpd>

    </div>

  </div>
</template>

<script setup lang='ts'>
import {ref,toRefs,reactive,} from 'vue';
import router from '../../router/router';
import moment from 'moment';  //时间
import { testList,del,deleteall,updateState } from "../../api/test";  //接口
import { ElMessage } from 'element-plus'
import FenYe from '../../components/fen ye/FenYe.vue' //分页
import Listdetails from "../../components/test/Listdetails.vue";  //考试名称 详情
import Examinee from '../../components/test/examinee.vue' // 学生
import seeteacherLook from "../../components/test/seeteacherLook.vue";  //可见老师
import yueTeacherUpd from "../../components/test/yueTeacherUpd.vue";


// 数据
const data = reactive<any>({
  mecheck: false, //我创建的
  timeRadio: '1', //日期选择 开放时间
  times: '', //时间
  stateValue: '', //表单状态选中数据
  options: [      //表单状态的数据
    {
      value: '0',
      label: '所有',
    },
    {
      value: '1',
      label: '已发布',
    },
    {
      value: '2',
      label: '未发布',
    },
  ],

  page: 1,
  psize: 10,
  Allid: [],
  shuttle: false,
  studentid: null,
});
const {
  mecheck,
  timeRadio,
  times,
  disabled,
  stateValue,
  options,
  page,
  psize,
  Allid,
} = toRefs(data);

// 列表数据

let data2:any = reactive({  //掉接口必要的参数
    page: 1,
    psize: 10,
    key: '',  //关键字
    state: 0, //状态
    admin: '',  //创建人
    ismy: '',   //只看我的
    opentime: '',  // 永久开放 部分时段
    begindate:"", //开始时间
    enddate:""    //结束时间
})

let testArr:any = ref([])  //赋值的数据
let totals:any = ref(0)  // 一共多少条数据

let getlist = async() => {
  // console.log(data2);
  
  let res = await testList(data2)
  console.log(res);
  testArr.value=res.data.list.map((item:any)=>({
    ...item,
    addtime: moment(item.addtime).format('YYYY-MM-DD hh:mm')  //处理时间
  }))
  totals.value = res.data.counts
}
getlist()


// 点击搜索
let search =() => {
  getlist()
}


// 点击复选框让按钮显示
let block = ref(0)
let deAll = ref([])
let handleSelectionChange = (val:any) => {
  // console.log(val);
  block.value = val.length; // 长度不等于零 v-show 显示按钮 否则隐藏

  deAll.value = val.map((item:any)=>item.id)  // 批删 获取到id
  console.log(deAll.value);
}

// 点击考试名称 出现弹窗
let detailsList = ref(false)  //弹窗默认关闭
let getid = ref(0)
let title = ref('')

let listdetails = (id: any, titles: any) => {
  detailsList.value = true  //弹窗
  getid.value = id
  title.value = titles
}

// 点击关闭弹窗
let closedetailsList = (val:boolean) => {
  // console.log(val);
  detailsList.value = val
}

// 状态
let updstate = async(val: any, id: number) => {
  // console.log(val, id);
  if(val===2){
    let res = await updateState({ state: 1,ids: [id]})
    // console.log(res);
    ElMessage({
      message: '发布成功',
      type: 'success',
    })
  }
  getlist()
}

// 时间快捷选项
const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 开放时间 永久开放--部分时段 时间切换状态
let Radio = (val:any) => { 
  console.log(val);
  data2.opentime = Number(val);

  getlist()
}

// 时间
let time = (val:any) => {
  // console.log(val);
  data2.begindate = moment(val[0]).format('YYYY-MM-DD hh:mm');  //开始时间
  data2.enddate = moment(val[1]).format('YYYY-MM-DD hh:mm');    //结束时间
  getlist()
}

// 状态搜索
const sele = (val: any) => {
  // console.log(val);
  data2.state = Number(val);  // 0 / 1 / 2
  getlist();
};

// 分页
const getChildData = (val:any) => {
  console.log(111, val)
  data2.page = val.page
  data2.psize = val.psize
  getlist()
}

// 单删
let getdel = async(val: any) => {
  // console.log(val);
  let res = await del({id:val})
  console.log(res);
  ElMessage({
    message: '删除成功',
    type: 'success',
  })
  getlist()
}

// 批删
let getdell = async() => {
  let res = await deleteall({ids:deAll.value})
  console.log("1",res);
  ElMessage({
    message: '删除成功',
    type: 'success',
  })
  getlist()
}

// 发布考试
let Publish = async() => {
  let res = await updateState({state:1,ids:deAll.value})
  console.log(res);
  ElMessage({
    message: '发布成功',
    type: 'success',
  })
  getlist()
}


// 取消发布
let cancel = async() => {
  let res = await updateState({state:2,ids:deAll.value})
  console.log(res);
  ElMessage({
    message: '取消成功',
    type: 'success',
  })
  getlist()
}

// 学生修改弹窗
let showStudent = ref(false) //默认不打开
let testId = ref(0) //id
let studentUpd = (id:any) => {
  showStudent.value = true
  testId.value = id
}

// 点击关闭学生弹窗
let StudenthandleClose = (val:any) =>{
  showStudent.value = val
}

// 学生弹窗取消按钮
let StudentCancels = (val:any) => {
  showStudent.value= val
}
// 学生弹窗确定按钮
let StudentConfirms = (val:any) => {
  showStudent.value = val
}


// 可见老师弹窗
let isshow = ref(false) //弹窗 默认关闭
let seeid = ref(0) //id
let SeeTeacherss = (id:any) => {
  isshow.value= true
  seeid.value = id
}

// 点击关闭可见老师弹窗
let handleClose = (val:any) => {
  isshow.value= val
}
// 可见老师弹窗取消按钮
let Cancel2 = (val:any) => {
  isshow.value= val
}
// 可见弹窗确定按钮
let Confirm = (val:any) => {
  isshow.value = val
}


// 阅卷老师
let isshow2 = ref(false) // 弹窗 默认关闭
let seeid2 = ref(0) //ID
let yueteacher = (id:any) =>{
  isshow2.value = true
  seeid2.value = id
}

// 关闭阅卷老师弹窗
let handleClosec = (val:any) => {
  isshow2.value = val
}
// 可见老师弹窗取消按钮
let Cancel3 = (val:any) => {
  isshow2.value= val
}
// 可见弹窗确定按钮
let Confirm3 = (val:any) => {
  isshow2.value = val
}


// 分析
let analysisTest = (val:any) => {
  // console.log(val);
  if (val.studentcounts == 0) {
    ElMessage({
      showClose: true,
      message: '没有学生考试',
      type: 'error',
    });
  } else if (val.isread == 1) {
    ElMessage({
      showClose: true,
      message: '该试卷未判完',
      type: 'error',
    });
  } else {
    router.push({
      path: './Analyse',
      query: { params: JSON.stringify(val) },
    });
  }
  
}

// 创建考试
let CaJN = () =>{
  router.push('./createTest')
}

// 点击编辑
const updTest = (id: any, val: any) => {
  if (val.studentcounts == 0) {
    router.push({
      path: '/createTest',
      query: { id: id },
    });
  } else {
    ElMessage({
      message: '本场考试已有学生参加，不可编辑',
      type: 'error',
    });
  }
};

</script>

<style scoped lang='less'>
.top {
  display: flex;
  justify-content: space-between;

  h2 {
    font-weight: normal
  }
}

.form {
  margin-top: 20px;
}

.span2 {
  font-size: 14px;
}
.button{
  margin-top: 20px;
  margin-bottom: 20px;
}
.fenye{
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.blues {
    font-size: 13px;
    color: #409eff;
}
.reds {
    font-size: 13px;
    color: rgb(245, 72, 72);
}

.reds:hover {
    border-bottom: 1px solid rgb(245, 72, 72);
    cursor: pointer
}
</style>